package xu.ye.uitl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.util.ArrayList;
import java.util.List;

import xu.ye.bean.ContactBean;
import android.os.Environment;

public class SDCardUtil {

	private static final String contactstPath = "/personManager";
	private static final String contactstFileName_Prefix = "contacts_person";
	//private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private File contactsFileName;
	private ObjectOutputStream objOs;
	private ObjectInputStream objIs;
	
	public SDCardUtil() throws Exception{
//		if(!isMounted()){
//			throw new Exception("SD卡未挂载");
//		}
		File dir = Environment.getExternalStorageDirectory();
		File targetDir = new File(dir.getPath()+contactstPath);
		if(!targetDir.exists()){
			targetDir.mkdir();
		}
		contactsFileName = new File(targetDir, contactstFileName_Prefix+".dat");
	}
	
    public	boolean isMounted(){
    	if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
    		return true;
    	}
    	return false;
    }
    
    
    public boolean write(ArrayList<ContactBean> list) throws IOException{
    	if (contactsFileName.exists()) { 
    		contactsFileName.delete();
        } 
    	contactsFileName.createNewFile(); 
    	
    	if(objOs == null){
    		objOs = new ObjectOutputStream(new FileOutputStream(contactsFileName));
    	}
    	boolean rs = false;
    	objOs.writeObject(list);
    	objOs.flush();
    	rs = true;
		return rs;
    }
    
   /* public void write(ContactBean cb){
		try {
			objOs.writeObject(cb);
		} catch (IOException e) {
			e.printStackTrace();
		}
    }*/
    
    public ArrayList<ContactBean> read() throws OptionalDataException,
    ClassNotFoundException, IOException {
    	if(objIs == null){
    		objIs = new ObjectInputStream(new FileInputStream(contactsFileName));
    	}
    	ArrayList<ContactBean> list = null;
    	list = (ArrayList<ContactBean>)objIs.readObject();
    	return list;
    }
    
    public void close(){
    	if(objOs!=null){
    		try {
				objOs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
    		objOs = null;
    	}
    	
    	if(objIs!=null){
    		try {
    			objIs.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			objIs = null;
    	}
    }
}
